package cn.itcast.bos.dao.base;

import java.io.Serializable; 
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import cn.itcast.bos.domain.PageBean;

public class BaseDaoImpl<T> extends HibernateDaoSupport implements IbaseDao<T> {

	//注入sessionFactoty
	@Resource
	public void setSF(SessionFactory sessionFactory){
		super.setSessionFactory(sessionFactory);
	}
	private Class<T> clazz;
	
	public BaseDaoImpl() {
		//获得父类类型
		ParameterizedType type  = (ParameterizedType) this.getClass().getGenericSuperclass();
		//获得泛型数组
		Type[] types = type.getActualTypeArguments();
		clazz = (Class<T>) types[0];
	}
	@Override
	public void save(T t) {
		this.getHibernateTemplate().save(t);
	}

	@Override
	public void delete(T t) {
		this.getHibernateTemplate().delete(t);
	}

	@Override
	public void update(T t) {
		this.getHibernateTemplate().update(t);
	}

	@Override
	public T findOne(Serializable id) {
		return this.getHibernateTemplate().get(clazz, id);
	}

	@Override
	public List<T> findAll() {
		String hql = "from "+clazz.getSimpleName();
		return this.getHibernateTemplate().find(hql);
	}

	@Override
	public List<T> findByCriteria(DetachedCriteria criteria) {
		return this.getHibernateTemplate().findByCriteria(criteria);
	}

	@Override
	public List<T> findByNamedQuery(String queryName, Object... args) {
		return this.getHibernateTemplate().findByNamedQuery(queryName, args);
	}
	@Override
	public void executeNamedQuery(String queryName, Object... args) {
		Session session = this.getSession();
		Query query = session.getNamedQuery(queryName);
		if (args != null && args.length > 0) {
			int i = 0;
			for (Object arg : args) {
				query.setParameter(i++, arg);
			}
		}
		query.executeUpdate();
	}

	public void pageQuery(PageBean pageBean) {
		int currentPage = pageBean.getCurrentPage();
		int pageSize = pageBean.getPageSize();
		DetachedCriteria detachedCriteria = pageBean.getDetachedCriteria();
		
		detachedCriteria.setProjection(Projections.rowCount());
		List<Long> list = this.getHibernateTemplate().findByCriteria(detachedCriteria);
		Long total = list.get(0);
		
		//查询当前页显示的数据集合
		detachedCriteria.setProjection(null);
		//指定hibernate框架从数据表中查询的每行对应的数据对应的包装成一个实体对象
		detachedCriteria.setResultTransformer(DetachedCriteria.ROOT_ENTITY);
		
		int firstResults = (currentPage-1)*pageSize;
		int maxResults = pageSize;
		List recordList = this.getHibernateTemplate().findByCriteria(detachedCriteria, firstResults, maxResults);
		pageBean.setTotal(total.intValue());
		pageBean.setRows(recordList);
	}
}
